package com.ray.controller.sys;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.ray.controller.base.BaseController;
import com.ray.log.WebLog;
import com.ray.model.DataButton;
import com.ray.model.Menu;
import com.ray.model.Permissions;
import com.ray.model.RolePermission;
import com.ray.util.Ret;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/permissions")
public class PermissionController extends BaseController {

    @Autowired
    private CacheManager cacheManager;

    /**
     * @note 获取菜单权限列表
     * @time 2024年03月26日 13:32:36
     * @author Ray
     */
    @RequestMapping("getList")
    @WebLog(description = "获取菜单权限列表")
    public Ret getList(String role_no) {
        List<Record> list = Db.use(base).find("select * from menu where parent_menu = 0 and is_hide = 0 and is_coder = 0 order by seq_num");
        list = tree(list);
        List<Permissions> temp = Permissions.dao.find("select * from permissions t1"
                + " left join role_permission t2 on t1.no = t2.permission_no"
                + " where t2.role_no = ?", role_no);
        String[] hasPermissions = new String[temp.size()];
        for (int i = 0; i < temp.size(); i++) {
            hasPermissions[i] = temp.get(i).getNo();
        }
        return Ret.ok("msg", "成功").setJson("list", list).set("hasPermissions", hasPermissions);
    }

    public List<Record> tree(List<Record> trees) {
        for (int i = 0; i < trees.size(); i++) {

            List<Record> temp = Db.use(base).find("select * from menu where parent_menu = ? and is_hide = 0 and is_coder = 0 order by seq_num", trees.get(i).getInt("id"));
            //当查询到最下级菜单后就查询权限表
            if (temp.size() == 0) {
                List<Permissions> list = Permissions.dao.find("select *,no as permissions_no,name as title from permissions where menu_no = ?", trees.get(i).getStr("no"));
                trees.get(i).set("children", list);
            } else {
                tree(temp);
                trees.get(i).set("children", temp);
            }
        }
        return trees;
    }

    /**
     * @note 权限分配修改
     * @time 2024年03月26日 13:34:09
     * @author Ray
     */
    @RequestMapping("update")
    @WebLog(description = "权限分配修改")
    @Transactional("baseTransactionManager")
    public Ret update(@RequestBody JSONObject param) {
        JSONArray permission_nos = param.getJSONArray("permission_nos");
        Db.use(base).delete("delete from role_permission where role_no = ?", param.getString("role_no"));
        RolePermission temp = null;
        String nos = "";
        for (int i = 0; i < permission_nos.size(); i++) {
            if (!nos.contains(permission_nos.getString(i))) {
                temp = new RolePermission();
                temp.setRegion(getSessionUserRegion());
                temp.setRoleNo(param.getString("role_no"));
                temp.setPermissionNo(permission_nos.getString(i));
                temp.save();
                nos += permission_nos.getString(i) + ",";
            }
        }
        return Ret.ok("msg", "保存权限成功");
    }

    /**
     * @note 根据现有菜单刷新权限列表
     * @time 2024年04月07日 16:44:13
     * @author Ray
     */
    @RequestMapping("refreshPermission")
    @WebLog(description = "刷新权限列表")
    public Ret refreshPermission() {
        Cache cache = cacheManager.getCache(base+"-permissions");
        if (cache != null) {
            cache.clear();
        }
        Db.use(base).update("delete from permissions where is_auto = 1");
        List<Menu> menus = Menu.dao.find("select * from menu where parent_menu != 0");
        for (Menu menu : menus){
            addPermission(menu);
        }
        return Ret.ok("msg", "刷新权限列表成功");
    }

    /**
     * @note 自动添加新建菜单的权限
     * @param menu
     */
    public void addPermission(Menu menu) {
        Permissions p = new Permissions();
        if (menu.getType() == 1) {
            //单表模型
            //查看
            p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_query").setName("查看").setType(1).setMenuNo(menu.getNo()).save();
            //新增
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_add").setName("新增").setType(2).setMenuNo(menu.getNo()).save();
            //修改
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_edit").setName("修改").setType(2).setMenuNo(menu.getNo()).save();
            //删除
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_del").setName("删除").setType(2).setMenuNo(menu.getNo()).save();
            List<DataButton> buttons = dataObjectService.getDataButtons(menu.getDataObjectNo());
            for (DataButton item : buttons) {
                p.remove("id");
                p.setNo(menu.getNo() + "_" + item.getPermissionNo()).setName(item.getPermissionName()).setType(2).setMenuNo(menu.getNo()).save();
            }
        } else if (menu.getType() == 2 || menu.getType() == 3 || menu.getType() == 4) {
            //查看
            p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_query").setName("查看").setType(1).setMenuNo(menu.getNo()).save();
            //主表新增
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_add").setName("主表新增").setType(2).setMenuNo(menu.getNo()).save();
            //主表修改
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_edit").setName("主表修改").setType(2).setMenuNo(menu.getNo()).save();
            //主表删除
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getDataObjectNo() + "_del").setName("主表删除").setType(2).setMenuNo(menu.getNo()).save();
            //子表新增
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getSonDataObjectNo() + "_add").setName("子表新增").setType(2).setMenuNo(menu.getNo()).save();
            //子表修改
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getSonDataObjectNo() + "_edit").setName("子表修改").setType(2).setMenuNo(menu.getNo()).save();
            //子表删除
            p.remove("id");
            p.setNo(menu.getNo() + "_" + menu.getSonDataObjectNo() + "_del").setName("子表删除").setType(2).setMenuNo(menu.getNo()).save();
            List<DataButton> buttons = dataObjectService.getDataButtons(menu.getDataObjectNo());
            for (DataButton item : buttons) {
                p.remove("id");
                p.setNo(menu.getNo() + "_" + item.getPermissionNo()).setName(item.getPermissionName()).setType(2).setMenuNo(menu.getNo()).save();
            }
        }
    }
}
